//
//  UIButton+MM_ConfigBtn.m
//  MallManage_IOS
//
//  Created by 张浩 on 2023/9/19.
//

#import "UIButton+MM_ConfigBtn.h"

@implementation UIButton (MM_ConfigBtn)

- (void)MM_ConfigButtonWithTitle:(NSString *)title
                       titleFont:(UIFont *)titleFont
                      titleColor:(UIColor *)titleColor
                         bgColor:(UIColor *)bgColor
                    cornerRadius:(CGFloat)cornerRadius
                     borderColor:(UIColor *)borderColor
                     borderWidth:(CGFloat)borderWidth {
    
    if (title) {
        [self setTitle:title forState:UIControlStateNormal];
    }
    if (titleFont) {
        self.titleLabel.font = titleFont;
    }
    if (titleColor) {
        [self setTitleColor:titleColor forState:UIControlStateNormal];
    }
    if (bgColor) {
        [self setBackgroundColor:bgColor];
    }
    if (cornerRadius >0) {
        self.layer.cornerRadius = cornerRadius;
    }
    if (borderColor) {
        self.layer.borderColor = borderColor.CGColor;
    }
    if (borderWidth >0) {
        self.layer.borderWidth = borderWidth;
    }
    self.layer.masksToBounds = YES;
    
}

- (void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state {
    
    [self setBackgroundImage:[self imageWithColor:color] forState:state];
}

- (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


- (UIEdgeInsets)clickEdgeInsets
{
    return [objc_getAssociatedObject(self, @selector(clickEdgeInsets)) UIEdgeInsetsValue];
}

- (void)setClickEdgeInsets:(UIEdgeInsets)clickEdgeInsets
{
    objc_setAssociatedObject(self, @selector(clickEdgeInsets), [NSValue valueWithUIEdgeInsets:clickEdgeInsets], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    
//    NSLog(@"%@",NSStringFromUIEdgeInsets(self.clickEdgeInsets));
    if (UIEdgeInsetsEqualToEdgeInsets(self.clickEdgeInsets, UIEdgeInsetsZero))
    {
        return [super pointInside:point withEvent:event];
    }
    else
    {
//        NSLog(@"%@",NSStringFromCGRect(self.bounds));
        CGRect large = UIEdgeInsetsInsetRect(self.bounds, self.clickEdgeInsets);
        return CGRectContainsPoint(large, point) ? YES : NO;
    }
}
@end
